package com.jf3q.front.service.impl;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.common.domain.EduOrder;
import com.jf3q.common.domain.EduPayLog;
import com.jf3q.common.exception.JfException;
import com.jf3q.common.mapper.EduPayLogMapper;
import com.jf3q.front.service.EduOrderService;
import com.jf3q.front.service.EduPayLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 *
 */
@Service
@Slf4j
public class EduPayLogServiceImpl extends ServiceImpl<EduPayLogMapper, EduPayLog>
    implements EduPayLogService {
    @Autowired
    EduOrderService orderService;

    @Autowired
    AlipayTradeService tradeService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Map createNatvie(String orderNo) {


        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = orderNo;

        //1 根据订单号查询订单信息
        LambdaQueryWrapper<EduOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduOrder::getOrderNo,orderNo);
        EduOrder order = orderService.getOne(wrapper);

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = order.getCourseTitle();//课程标题

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount =  order.getTotalFee()+"";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";
        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        String body = "购买课程"+order.getCourseTitle()+"消费"+order.getTotalFee()+"元";
        // 支付超时，定义为24小时
        String timeoutExpress = "24h";
        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";
        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        GoodsDetail goods1 = GoodsDetail.newInstance(order.getCourseId(), order.getCourseTitle(),  order.getTotalFee().multiply(new BigDecimal("100")).longValue(), 1);
        // 创建好一个商品后添加至商品明细列表
        goodsDetailList.add(goods1);
        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setSellerId(sellerId).setBody(body)
                .setStoreId(storeId)
                .setTimeoutExpress(timeoutExpress)
                .setGoodsDetailList(goodsDetailList);

        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("支付宝预下单成功: )");

                AlipayTradePrecreateResponse response = result.getResponse();

                Map map = new HashMap();
                map.put("out_trade_no", orderNo);
                map.put("course_id", order.getCourseId());
                map.put("total_fee", order.getTotalFee());
                map.put("code_url", response.getQrCode());
                return map;
            default:
                throw  new RuntimeException(result.getResponse().getSubMsg());
        }
    }

    @Override
    public void queryPayStatus(String orderNo) {
        // (必填) 商户订单号，通过此商户订单号查询当面付的交易状态
        String outTradeNo = orderNo;
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder()
                .setOutTradeNo(outTradeNo);
        AlipayF2FQueryResult result = tradeService.queryTradeResult(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("查询返回该订单支付成功: )");

                //支付成功之后的业务逻辑

                //1 根据订单号查询订单信息
                LambdaQueryWrapper<EduOrder> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(EduOrder::getOrderNo,orderNo);
                EduOrder order = orderService.getOne(wrapper);

                //更新订单表订单状态
                if(order.getStatus().intValue() == 1) { return; }
                order.setStatus(Byte.valueOf("1"));//1代表已经支付
                orderService.updateById(order);
                //向支付表添加支付记录
                EduPayLog payLog = new EduPayLog();
                payLog.setOrderNo(orderNo);  //订单号
                payLog.setPayTime(new Date()); //订单完成时间
                payLog.setPayType( Byte.valueOf("2"));//支付类型 1微信 2支付宝
                payLog.setTotalFee(order.getTotalFee());//总金额(分)

                payLog.setTradeState(result.getResponse().getTradeStatus());//支付状态
                payLog.setTransactionId(result.getResponse().getTradeNo()); //支付宝交易号
                baseMapper.insert(payLog);

                //修改了购买数
                redisTemplate.opsForHash().increment("course_" + order.getCourseId(), "buyCount", 1);
                //讲师排行数据
                Double teacherBuyCount = redisTemplate.opsForZSet().score("teacherBuyCount", order.getTeacherId());
                redisTemplate.opsForZSet().add("teacherBuyCount",order.getTeacherId(),teacherBuyCount==null?1:teacherBuyCount+1);
                break;
            default:
                throw new JfException(25000,"支付中……");
        }
    }
}




